package com.cltech.controller.sys;

import com.cltech.entity.sys.SysExceptionLog;
import com.cltech.frame.result.ResponseBean;
import com.cltech.frame.utils.JWTUtil;
import com.cltech.service.sys.SysExceptionLogService;
import org.apache.shiro.ShiroException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by Administrator on 2018/9/9.
 */
@RestControllerAdvice
public class ExceptionController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionController.class);
    @Autowired
    private SysExceptionLogService sysExceptionLogService;
    // 捕捉shiro的异常
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(ShiroException.class)
    public ResponseBean handle401(ShiroException e) {
        return ResponseBean.error(401, e.getMessage());
    }

     // 捕捉其他所有异常
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseBean globalException(HttpServletRequest request, Throwable e) {
        e.printStackTrace();
        LOGGER.error("服务器错误", e.getMessage());
        String authorization = request.getHeader("Authorization");
        SysExceptionLog sysExceptionLog = new SysExceptionLog();
        if(null != authorization){
            String userId = JWTUtil.getUserId(authorization);
            sysExceptionLog.setOperator(userId);
        }
        final String servletPath = request.getServletPath();
        sysExceptionLog.setPath(servletPath);
        sysExceptionLog.setMessage(e.getMessage());
        sysExceptionLog.setCreateTime(new Date());
        sysExceptionLogService.asyncSave(sysExceptionLog);
        return ResponseBean.error(getStatus(request).value(), "服务器错误");
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}
